package com.ymt.bpm.service.platform.config.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ymt.bpm.dao.MDao;
import com.ymt.bpm.dao.Mapper;
import com.ymt.bpm.model.Const.Oplog;
import com.ymt.bpm.model.PService;
import com.ymt.bpm.service.platform.config.SvcService;
import com.ymt.bpm.service.platform.log.OpLogService;
import com.ymt.bpm.util.Const;
import com.ymt.bpm.util.DateUtil;
import com.ymt.bpm.util.DhxUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Service
public class SvcServiceImpl implements SvcService {

    /**
     * Logger
     */
    private Logger log = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private MDao dao;

    @Autowired
    private OpLogService oplog;

    @Override
    public JSONObject query(String tenantId, String appId, String search, String sort, String order, int offset, int limit, int timezoneOffset) {
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put(Const.TENANT_ID, tenantId);
        paramMap.put("search", search);
        paramMap.put("appId", appId);
        paramMap.put("sort", sort);
        paramMap.put("order", order);
        PageHelper.offsetPage(offset, limit);
        List<PService> list = dao.selectList(Mapper.PServiceMapper, "query", paramMap);
        PageInfo pageInfo = new PageInfo(list);
        JSONObject rtn = new JSONObject();
        JSONArray rows = new JSONArray();
        if (list!=null && list.size()>0) {
            for (PService svc : list) {
                JSONObject node = DhxUtil.toJsonWithDateAli(svc, Const.LANG_ZH, timezoneOffset);
                node.put("_ITEM_NO", ++offset);
                rows.add(node);
            }
        }
        rtn.put("rows", rows);
        rtn.put("total", pageInfo.getTotal());
        return rtn;
    }

    /**
     * get service
     * @param id
     * @return
     */
    @Override
    public JSONObject get(String tenantId, String id, String lang, int timezoneOffset) {
        Map<String, Object> paramMap = new HashMap<String, Object>();
        if (tenantId!=null && StringUtils.isNumeric(tenantId)) {
            paramMap.put(Const.TENANT_ID, Integer.parseInt(tenantId));
        }
        paramMap.put("id", id);
        PService bo = dao.selectOne(Mapper.PServiceMapper, "selectByPrimaryKey", paramMap);
        JSONObject cfg = JSONObject.parseObject(bo.getSvcConfig());//turn string to object
        bo.setSvcConfig(null);
        JSONObject bojo = DhxUtil.toJsonWithDate(bo, lang, timezoneOffset);
        bojo.put("svcConfig", cfg);
        return bojo;
    }

    /**
     * save service
     * @param bo
     * @param loginName
     * @param displayName
     * @return
     */
    @Override
    public JSONObject save(String tenantId, PService bo, String loginName,
                       String displayName) {
        String id = bo.getId();
        if (id==null || id.length()==0) {
            id = "SVC-"+ UUID.randomUUID().toString();
            bo.setId(id);
            if (tenantId!=null && org.apache.commons.lang.StringUtils.isNumeric(tenantId)) {
                bo.setTenantId(tenantId);
            }
            bo.setStatus("00");
            bo.setCreator(loginName);
            bo.setCreatorName(displayName);
            bo.setCreateTime(DateUtil.getGMTDate());
            bo.setUpdator(loginName);
            bo.setUpdatorName(displayName);
            bo.setUpdateTime(DateUtil.getGMTDate());
            dao.insert(Mapper.PServiceMapper, "insert", bo);

            //记录日志
            oplog.bizlog(tenantId, loginName, displayName, null, Oplog.OP.CREATE, Oplog.CODE.SERVICE, bo.getSvcDesc());
        } else {
            if (tenantId!=null && StringUtils.isNumeric(tenantId)) {
                bo.setTenantId(tenantId);
            }
            bo.setUpdator(loginName);
            bo.setUpdatorName(displayName);
            bo.setUpdateTime(DateUtil.getGMTDate());
            dao.update(Mapper.PServiceMapper, "updateByPrimaryKeySelective", bo);
            id = bo.getId();

            //记录日志
            oplog.bizlog(tenantId, loginName, displayName, null, Oplog.OP.UPDATE, Oplog.CODE.SERVICE, bo.getSvcDesc());
        }
        JSONObject rtn = new JSONObject();
        rtn.put(Const.AJAX_RESULT, true);
        rtn.put("id", id);
        return rtn;
    }

    /**
     * delete service
     * @param id
     * @return
     */
    @Override
    public JSONObject delete(String tenantId, String loginName,
                             String displayName,
                             String id) {
        if (log.isDebugEnabled()) {
            log.debug("delete id="+id);
        }
        Map<String, Object> paramMap = new HashMap<String, Object>();
        if (tenantId!=null && StringUtils.isNumeric(tenantId)) {
            paramMap.put(Const.TENANT_ID, Integer.parseInt(tenantId));
        }
        paramMap.put("id", id);
        PService service = dao.selectOne(Mapper.PServiceMapper, "selectByPrimaryKey", paramMap);
        JSONObject rtn = new JSONObject();
        int rs = dao.delete(Mapper.PServiceMapper, "deleteByPrimaryKey", paramMap);
        rtn.put(Const.AJAX_RESULT, rs);

        //记录日志
        oplog.bizlog(tenantId, loginName, displayName, null, Oplog.OP.DELETE, Oplog.CODE.SERVICE, service.getSvcDesc());

        return rtn;
    }

    @Override
    public String checkAttr(String tenantId, String attrName, String value, String id) {
        if (log.isDebugEnabled()) {
            log.debug("checkAttr tenantId="+tenantId);
            log.debug("checkAttr attrName="+attrName);
            log.debug("checkAttr value="+value);
            log.debug("checkAttr id="+id);
        }
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("tenantId", tenantId);
        paramMap.put("value", value);
        paramMap.put("id", id);
        int rs = dao.selectOne(Mapper.PServiceMapper, "checkAttr"+ org.springframework.util.StringUtils.capitalize(attrName), paramMap);
        if (log.isDebugEnabled()) {
            log.debug("checkAttr rs="+rs);
        }
        return rs>0 ? "false" : "true";
    }

}
